package com.tzg.iot.http.service;

import com.alibaba.fastjson.JSONObject;
import com.tzg.iot.http.info.HostInfo;
import com.tzg.iot.http.util.HttpClientUtil;
import com.tzg.iot.http.util.TokenUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

/**
 * @author tzg157
 */
public class DeviceService {

    /**
     * 获取设备列表
     * @param limit
     * @param searchText
     * @return
     * @throws IOException
     */
    public List<Map<String,Object>> deviceList(int limit,String searchText) throws IOException {
        if(TokenUtil.token == null || TokenUtil.token.equals("")) {
            throw new NullPointerException("token不能为空!");
        }

//        InputStream inputStream =
//                HttpClientUtil.get(HostInfo.HOST,HostInfo.PORT,HostInfo.TENANT_DEVICE_LIST_PATH,null,TokenUtil.token);
        InputStream inputStream =
                HttpClientUtil.get(HostInfo.HTTP_PROTOCOL + HostInfo.HOST + ":" + HostInfo.PORT + HostInfo.TENANT_DEVICE_LIST_PATH
                        + "?limit=" + limit + "&" + "textSearch=" + searchText,null,TokenUtil.token);
        InputStreamReader reader = new InputStreamReader(inputStream);
        //读取字符流
        BufferedReader bufferedReader = new BufferedReader(reader);
        String data = null;
        String jsonStr = "";
        while ((data = bufferedReader.readLine()) != null) {
            System.out.println(data);
            if(data.startsWith("{")){
                jsonStr = data;
                break;
            }
        }
        //json字符串转换为map
        Map<String,Object> jsonMap = JSONObject.parseObject(jsonStr);
        if(jsonMap != null){
            List<Map<String,Object>> ret = (List<Map<String, Object>>) jsonMap.get("data");
            return ret;
        }
        return null;
    }

    /**
     * 获取设备id
     * @param deviceMap
     * @return
     */
    public String getDeviceId(Map<String,Object> deviceMap){
        Map<String,Map<String,Object>> idMap = (Map<String, Map<String, Object>>) deviceMap.get("id");
        String deviceId = String.valueOf(idMap.get("id"));
        return deviceId;
    }

    /**
     * 获取设备授权码
     * @param deviceId
     * @return
     */
    public String getCredentials(String deviceId) throws IOException {
        String url = HostInfo.HTTP_PROTOCOL + HostInfo.HOST + ":" + HostInfo.PORT + HostInfo.TENANT_DEVICE_CREDENTIALS;
        url = String.format(url,deviceId);
        InputStream inputStream =
                HttpClientUtil.get(url,null,TokenUtil.token);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String credentialStr = reader.readLine();
        Map<String,Object> data = JSONObject.parseObject(credentialStr,Map.class);
        if(data != null){
            return String.valueOf(data.get("credentialsId"));
        }
        return "";
    }
}
